package com.ruoyi.system.utils;

import com.ruoyi.system.domain.dto.TestPowerHeartrateDTO;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 上传数据转换工具类
 */
public class UploadDataChangeUtils {

    /**
     * 添加字段为0的字段名
     * @param builder
     * @param value
     * @param name
     */
    public static void appendIfZero(StringBuilder builder, Integer value, String name) {
        if (value != null && value == 0) {
            builder.append(name).append("、");
        }
    }

    // 特殊处理：需要额外值的字段
    public static void appendSgzgIfZero(StringBuilder builder, Integer sgzg, Object sgzgval) {
        if (sgzg != null && sgzg == 0) {
            String value = (sgzgval != null) ? sgzgval.toString() : "";
            builder.append("身高/坐高(").append(value).append(")、");
        }
    }

    /**
     * 添加字段为0的字段名
     * @param builder
     * @param fieldValue
     * @param extraValue
     * @param prefix
     */
    public static void appendWithValue(StringBuilder builder, Integer fieldValue, Object extraValue, String prefix) {
        if (fieldValue != null && fieldValue == 0) {
            String value = (extraValue != null) ? extraValue.toString() : "";
            builder.append(prefix).append("(").append(value).append(")、");
        }
    }

    /**
     * 特殊处理俯卧撑、跪卧撑
     * @param builder
     * @param fwcValue
     * @param gwcValue
     */
    public static void appendFwcGwc(StringBuilder builder, Integer fwcValue, Integer gwcValue) {
        Integer value = fwcValue != null ? fwcValue : gwcValue;
        if (value != null && value == 0) {
            builder.append("俯卧撑/跪卧撑、");
        }
    }

    /**
     * 移除多余的顿号
     * @param builder
     */
    public static void removeLastComma(StringBuilder builder) {
        if (builder.length() > 0 && builder.charAt(builder.length() - 1) == '、') {
            builder.deleteCharAt(builder.length() - 1);
        }
    }

    /**
     * 添加字段为0的字段名
     * @param builder
     * @param value
     * @param name
     */
    public static void appendIfZeroSafe(StringBuilder builder, Integer value, String name) {
        if (value != null && value == 0) {
            builder.append(name).append("、");
        }
    }

    /**
     * 安全转换成Float
     * @param value
     * @return
     */
    public static Float toSafeFloat(Double value) {
        if (value == null || value.isNaN() || value.isInfinite()) {
            return null;
        }
        return value.floatValue();
    }

    /**
     * 安全比较
     * @param value
     * @param target
     * @return
     */
    public static boolean safeGreaterOrEqual(Float value, float target) {
        if (value == null) return false;

        // 处理浮点精度问题
        final float EPSILON = 0.001f; // 根据业务需求调整精度
        return value - target > -EPSILON;
    }

    // 安全转换并比较
    public static boolean isAgeAboveThreshold(Double ageValue, float threshold) {
        if (ageValue == null) return false;

        try {
            float age = ageValue.floatValue();
            return safeGreaterOrEqual(age, threshold);
        } catch (Exception e) {
            return false; // 处理任何可能的异常
        }
    }

    // 获取心率
    public static String getheartRate(String glcHeartRate, TestPowerHeartrateDTO heartrate) {
        if (glcHeartRate == null) {
            if(heartrate!=null && heartrate.getHeartrate()!=null) {
                return heartrate.getHeartrate();
            }
        }
        if (heartrate == null) {
            return glcHeartRate;
        }
        if (heartrate.getHeartrate() == null) {
            return glcHeartRate;
        }
        return glcHeartRate + "," + heartrate;
    }

    public static String truncateToMonthWithoutZeroPadFast(String dateStr) {
        if (dateStr == null || dateStr.length() < 7) {
            throw new IllegalArgumentException("日期字符串长度不足");
        }

        try {
            // 直接提取年份部分（前4字符）

            // 提取月份部分并去除前导零
            String monthPart = dateStr.substring(5, 7);
            int month = Integer.parseInt(monthPart);

            return String.valueOf(month);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("月份部分包含非数字字符", e);
        }
    }

    /**
     * 安全转换成字符串
     * @param value
     * @return
     */
    public static String safeDoubleToString(Double value) {
        return (value == null || Double.isNaN(value)) ? "" : value.toString();
    }

    public static String joinDoubles(String delimiter, Double... values) {
        return Arrays.stream(values)
                .map(UploadDataChangeUtils::safeDoubleToString)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.joining(delimiter));
    }



    /**
     * 将坐标字符串转换为十进制值（自动判断格式）
     */
    public static double parseCoordinate(String coord) {
        if (coord == null || coord.isEmpty()) return 0.0;

        // 如果是度分秒格式
        if (coord.contains("°") || coord.contains("度")) {
            return dmsToDecimal(coord);
        }

        // 直接解析十进制
        return Double.parseDouble(coord);
    }

    /**
     * 将度分秒格式的GPS坐标转换为十进制格式
     * 支持格式：39°43′51″ 或 39度43分51秒
     */
    public static double dmsToDecimal(String dms) {
        if (dms == null || dms.isEmpty()) return 0.0;

        // 统一替换中文符号
        String normalized = dms.replace("度", "°")
                .replace("分", "′")
                .replace("秒", "″");

        // 提取度、分、秒
        String[] parts = normalized.split("[°′″]");
        if (parts.length < 3) {
            throw new IllegalArgumentException("无效的度分秒格式: " + dms);
        }

        double degrees = Double.parseDouble(parts[0]);
        double minutes = Double.parseDouble(parts[1]);
        double seconds = parts.length > 2 ? Double.parseDouble(parts[2]) : 0.0;

        // 计算十进制
        return degrees + (minutes / 60.0) + (seconds / 3600.0);
    }


    public static void appendIfZero1(StringJoiner message, Integer value, String fieldName) {
        if (value != null && value == 0) {
            message.add(fieldName);
        }
    }

    public static void appendIfZeroSafe1(StringJoiner message, Integer value, String fieldName) {
        if (value != null && value == 0) {
            message.add(fieldName);
        }
    }

    public static void appendWithValue1(StringJoiner message, Integer status, String value, String fieldName) {
        if (status != null && status == 0) {
            message.add(fieldName + (value != null ? "(" + value + ")" : ""));
        }
    }

    public static void appendSgzgIfZero1(StringJoiner message, Integer sgzg, String sgzgval) {
        if (sgzg != null && sgzg == 0) {
            message.add("身高坐高比" + (sgzgval != null ? "(" + sgzgval + ")" : ""));
        }
    }

    public static String extractTestYear(List<Map<String, Object>> outerList, String innerKey) {
        if (outerList == null || outerList.isEmpty()) return null;

        Map<String, Object> firstOuter = outerList.get(0);
        Object innerData = firstOuter.get(innerKey);
        if (innerData instanceof List) {
            List<?> innerList = (List<?>) innerData;
            if (!innerList.isEmpty() && innerList.get(0) instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> firstInner = (Map<String, Object>) innerList.get(0);
                Object testTime = firstInner.get("testTime");
                if (testTime != null) {
                    return testTime.toString().substring(0, 4);
                }
            }
        }
        return null;
    }
}
